package battleship;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;

public class CancelNewGameServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("CancelNewGameServlet: started");
        
    	String userToken= request.getParameter("token");
    	int id= (Integer) UserIdTokenHashMap.idTokenMap.get(userToken);
    	
    //    int id = Integer.parseInt(request.getParameter("id"));
        User user = Context.users[id];

        Context.openGames.remove(user.game);
        System.out.println("CancelNewGameSevlet: removed a game from the global open games list");
        Iterator<User> userIterator = Context.onlineUsers.iterator();
        while(userIterator.hasNext()) {
            User otherUser = userIterator.next();
            try {
                otherUser.oldOpenGames.put(user.game);
            } catch (InterruptedException e) {
                System.out.println("CancelNewGameServlet InterruptedException: " + e.getMessage());
            }
        }
        user.game = new Game();
        user.waitingForOpponent = false;
        // because there will still be a take() method waiting on the old queue, we don't want that to interfere if
        // we open a new game
        user.waitForJoin = new LinkedBlockingQueue<User>();
        System.out.println("CancelNewGameServlet: finished");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
